#include "mainwindow.h"
#include "ui_MainWindow.h"

bool isInteger(const QString& input)
{
    static QRegularExpression re("^[-+]?\\d+$");
    QRegularExpressionMatch match = re.match(input);
    return match.hasMatch();
}

void MainWindow::initPlot(QCustomPlot* q, int xCount)
{
    QVector<QColor> colors = {
        Qt::red, QColor(255, 215, 0), Qt::blue, QColor(178, 34, 34), Qt::magenta, Qt::yellow, Qt::black,
        QColor(255, 99, 71), Qt::white
    };
    q->legend->setVisible(true);
    q->legend->setBrush(QColor(255, 255, 255, 150));
    q->legend->setBorderPen(Qt::NoPen);
    q->xAxis->setRange(0, xCount);
    q->xAxis->setLabelColor(Qt::white);
    q->yAxis->setLabelColor(Qt::white);
    q->xAxis->setBasePen(QPen(Qt::white));
    q->yAxis->setBasePen(QPen(Qt::white));
    q->setBackground(QColor(Qt::gray));
    q->selectionRect()->setPen(QPen(Qt::black, 1, Qt::DashLine)); //设置选框的样式：虚线
    q->selectionRect()->setBrush(QBrush(QColor(0, 0, 100, 50)));
    for (int i = 0; i < 9; ++i)
    {
        QCPGraph* graph = q->addGraph();
        graph->setVisible(false);
        graph->setPen(QPen(colors[i], 3));
        if (i == 8)
        {
            graph->setVisible(true);
            graph->setName(QString("校准通道"));
            break;
        }
        graph->setName(QString("通道 %1").arg(i + 1));
    }
    q->replot();
}

MainWindow::MainWindow(QWidget* parent) :
    QWidget(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->comboBox->addItem(info.portName());
    }
    rec = new Receiver();
    thread = new QThread(this);
    rec->moveToThread(thread);
    thread->start();
    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::open);
    connect(this, &MainWindow::openS, rec, &Receiver::openS);
    connect(this, &MainWindow::closeS, rec, &Receiver::closeS);
    connect(rec, &Receiver::changePushButton, this, &MainWindow::changePushButton);
    timer = new QTimer(this);
    timer->setInterval(100);
    // timer2 = new QTimer(this);
    // timer2->setInterval(10);
    connect(timer, &QTimer::timeout, this, [=]()
    {
        ui->graphicsView->replot();
    });
    timerForStartAutoXY = new QTimer(this);
    connect(timerForStartAutoXY, &QTimer::timeout, [=]()
    {
        // ui->pushButton_5->clicked();
        changeXY();
    });
    // timerForStartAutoXY->setSingleShot(true);
    // connect(rec, &Receiver::noMoreData, this, &MainWindow::close);
    ui->pushButton_10->setCheckable(true);
    ui->pushButton_10->setChecked(true);
    connect(ui->pushButton_10, &QPushButton::clicked, [=]()
    {
        if(ui->pushButton_10->isChecked())
        {
            ui->graphicsView->graph(8)->setVisible(true);
        }else
        {
            ui->graphicsView->graph(8)->setVisible(false);
        }
    });
    ui->lineEdit->setPlaceholderText("请输入中轴线坐标");
    ui->lineEdit_2->setPlaceholderText("请输入坐标跨度(取绝对值)");
    connect(ui->pushButton_7, &QPushButton::clicked, [=]()
    {
        if(ui->lineEdit_3->text().toDouble()==0)
        {
            qDebug() << "0";
        }
            emit changeAB(ui->lineEdit_3->text().toDouble(), ui->lineEdit_4->text().toDouble(),ui->comboBox_2->currentIndex());
    });
    connect(this, &MainWindow::changeAB, rec, &Receiver::changeAB);
    ui->lineEdit_3->setText(QString::number(rec->aVector[0]));
    ui->lineEdit_4->setText(QString::number(rec->bVector[0]));
    connect(ui->comboBox_2, &QComboBox::currentIndexChanged, [=](int index)
    {
        ui->lineEdit_3->setText(QString::number(rec->aVector[index]));
        ui->lineEdit_4->setText(QString::number(rec->bVector[index]));
    });
    connect(ui->pushButton_4, &QPushButton::clicked, [=]()
    {
        auto list = findChildren<QCheckBox*>();
        if (ui->pushButton_4->text() == "select all")
        {
            for (auto& i : list)
            {
                i->setChecked(true);
            }
            ui->pushButton_4->setText("select none");
        }
        else
        {
            for (auto& i : list)
            {
                i->setChecked(false);
            }
            ui->pushButton_4->setText("select all");
        }
    });
    ui->pushButton_9->setCheckable(true);
    ui->pushButton_8->setCheckable(true);
    initPlot(ui->graphicsView, 10000);
    initPlot(ui->graphicsView_2, 1000);
    auto list = findChildren<QCheckBox*>();
    int tempIndex = 0;
    for (auto& i : list)
    {
        connect(i, &QCheckBox::stateChanged, [=](int state)
                {
                    if (state == Qt::Checked)
                    {
                        ui->graphicsView->graph(tempIndex)->setVisible(true);
                        ui->graphicsView_2->graph(tempIndex)->setVisible(true);
                    }
                    else
                    {
                        ui->graphicsView->graph(tempIndex)->setVisible(false);
                        ui->graphicsView_2->graph(tempIndex)->setVisible(false);
                    }
                    ui->graphicsView->replot();
                    ui->graphicsView_2->replot();
                }
        );
        tempIndex++;
    }
    ui->pushButton_5->setCheckable(true);
    connect(ui->pushButton_5, &QPushButton::clicked, [=]()
    {
        if(ui->pushButton_5->isChecked())
        {
            timerForStartAutoXY->start(200);
        }else
        {
            timerForStartAutoXY->stop();
        }
    });
    connect(ui->pushButton_9, &QPushButton::clicked, [=]()
    {
        ui->pushButton_8->setChecked(false);
        if (ui->pushButton_9->isChecked())
        {
            ui->graphicsView->setInteraction(QCP::iRangeDrag, false);
            ui->graphicsView->setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
            ui->graphicsView_2->setInteraction(QCP::iRangeDrag, false);
            ui->graphicsView_2->setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
        }
        else
        {
            ui->graphicsView->setInteraction(QCP::iRangeDrag, false);
            ui->graphicsView->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
            ui->graphicsView_2->setInteraction(QCP::iRangeDrag, false);
            ui->graphicsView_2->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
        }
    });
    connect(ui->pushButton_8, &QPushButton::clicked, [=]()
    {
        ui->pushButton_9->setChecked(false);
        if (ui->pushButton_8->isChecked())
        {
            ui->graphicsView->setInteraction(QCP::iRangeDrag, true);
            ui->graphicsView->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
            ui->graphicsView_2->setInteraction(QCP::iRangeDrag, true);
            ui->graphicsView_2->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
        }
        else
        {
            ui->graphicsView->setInteraction(QCP::iRangeDrag, false);
            ui->graphicsView->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
            ui->graphicsView_2->setInteraction(QCP::iRangeDrag, false);
            ui->graphicsView_2->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
        }
    });
    connect(ui->pushButton_3, &QPushButton::clicked, [=]()
    {
        if (isInteger(ui->lineEdit->text()) && isInteger(ui->lineEdit_2->text()))
        {
            ui->graphicsView->yAxis->setRange(ui->lineEdit->text().toInt() - abs(ui->lineEdit_2->text().toInt()) / 2,
                                              ui->lineEdit->text().toInt() + abs(ui->lineEdit_2->text().toInt()) / 2);
            ui->graphicsView_2->yAxis->setRange(ui->lineEdit->text().toInt() - abs(ui->lineEdit_2->text().toInt()) / 2,
                                                ui->lineEdit->text().toInt() + abs(ui->lineEdit_2->text().toInt()) / 2);
            ui->graphicsView->xAxis->setRange(0, 10000);
            ui->graphicsView_2->xAxis->setRange(0, 1000);
            ui->graphicsView->replot();
            ui->graphicsView_2->replot();
        }
    });
    connect(ui->lineEdit, &QLineEdit::textChanged, [=](const QString& text)
    {
        if (isInteger(text) || text.isEmpty())
        {
            ui->lineEdit->setStyleSheet("QLineEdit { color: black; }");
        }
        else
        {
            ui->lineEdit->setStyleSheet("QLineEdit { color: red;}");
        }
    });
    connect(ui->lineEdit_2, &QLineEdit::textChanged, [=](const QString& text)
    {
        if (isInteger(text) || text.isEmpty())
        {
            ui->lineEdit_2->setStyleSheet("QLineEdit { color: black; }");
        }
        else
        {
            ui->lineEdit_2->setStyleSheet("QLineEdit { color: red;}");
        }
    });
    connect(ui->pushButton_2, &QPushButton::clicked, [=]()
    {
        if (ui->stackedWidget->currentIndex() == 0)
        {
            ui->stackedWidget->setCurrentIndex(1);
        }
        else
        {
            ui->stackedWidget->setCurrentIndex(0);
        }
    });
    connect(ui->pushButton_6, &QPushButton::clicked, [=]()
    {
        emit clear(ui->stackedWidget->currentIndex());
    });
    connect(this, &MainWindow::clear, rec, &Receiver::clearGR);
    rec->plot = ui->graphicsView;
    rec->plot2 = ui->graphicsView_2;
    rec->plot->setOpenGl(true);
    ui->radioButton->setChecked(true);
    connect(ui->radioButton, &QRadioButton::clicked, [=]()
    {
        if (ui->radioButton->isChecked())
        {
            ui->graphicsView->legend->setVisible(true);
            ui->graphicsView_2->legend->setVisible(true);
            ui->graphicsView->replot();
            ui->graphicsView_2->replot();
        }
        else
        {
            ui->graphicsView->legend->setVisible(false);
            ui->graphicsView_2->legend->setVisible(false);
            ui->graphicsView->replot();
            ui->graphicsView_2->replot();
        }
    });
    ui->pushButton_4->clicked();
}

MainWindow::~MainWindow()
{
    thread->quit();
    delete ui;
}

void MainWindow::open()
{
    emit clear(ui->stackedWidget->currentIndex());
    if (ui->pushButton->text() == "init")
    {
        emit openS(ui->comboBox->currentText());
    }
    else if (ui->pushButton->text() == "close")
    {
        emit closeS();
    }
}

void MainWindow::changePushButton(bool o)
{
    if (o)
    {
        ui->pushButton->setText("close");
        timer->start();
    }
    else
    {
        ui->pushButton->setText("init");
        timer->stop();
    }
}

void MainWindow::changeXY()
{
    ui->graphicsView->rescaleAxes(true);
    ui->graphicsView_2->rescaleAxes(true);
    ui->graphicsView->xAxis->setRange(0, 10000);
    ui->graphicsView_2->xAxis->setRange(0, 1000);
    QCPRange yRange = ui->graphicsView->yAxis->range();
    double minY = yRange.lower - (yRange.size() / 10);
    double maxY = yRange.upper + (yRange.size() / 10);
    QCPRange yRange2 = ui->graphicsView_2->yAxis->range();
    double minY2 = yRange2.lower - (yRange2.size() / 10);
    double maxY2 = yRange2.upper + (yRange2.size() / 10);
    ui->graphicsView->yAxis->setRange(minY, maxY);
    ui->graphicsView_2->yAxis->setRange(minY2, maxY2);
}
